//
//  UserViewController.swift
//  AutoPrint
//
//  Created by David on 16/10/22.
//  Copyright © 2016年 fatcat. All rights reserved.
//

import UIKit

class UserViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate {

    let CACHES_PATH = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true).first!
    let ASK_QUIT_LOGIN_ALERT_ID = 101
    
    let titleForItems = ["用户名","头像"]
    
    var tableView: UITableView!
    
    var quitLoginBtn: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "个人资料"
        tableView = UITableView(frame: view.frame, style: .Grouped)
        view.addSubview(tableView)
        tableView.delegate = self
        tableView.dataSource = self
        //navigationController?.navigationBar.hidden = false
        
        let fakeNavBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 64))
        view.addSubview(fakeNavBar)
        fakeNavBar.barTintColor = Fatcat.THEME_COLOR
        fakeNavBar.barStyle = .Black
        fakeNavBar.tintColor = UIColor.whiteColor()
        let fakeNavItem = UINavigationItem(title: title!)
        let fakeBackButton = UIBarButtonItem()
        fakeBackButton.title = "    返回"
        fakeNavItem.leftBarButtonItem = fakeBackButton
        
        fakeNavBar.pushNavigationItem(fakeNavItem, animated: false)
        
        //navigationItem.leftBarButtonItem = fakeBackButton
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        navigationController?.navigationBar.hidden = false
    }
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            return titleForItems.count
        }
        return 1
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .Default, reuseIdentifier: "info")
        if indexPath.section == 0{
            let titleLabel = UILabel(frame: CGRect(x: 16, y: 8, width: (view.bounds.width-32)/2, height: 28))
            cell.addSubview(titleLabel)
            
            let detailLabel = UILabel(frame: CGRect(x: view.bounds.width/2, y: 8, width: (view.bounds.width-32)/2, height: 28))
            detailLabel.textColor = UIColor.lightGrayColor()
            detailLabel.textAlignment = .Right
            cell.addSubview(detailLabel)
            
            titleLabel.text = titleForItems[indexPath.row]
            
            switch indexPath.row {
            case 0:
                if NSUserDefaults.standardUserDefaults().objectForKey("user") != nil {
                    detailLabel.text = NSUserDefaults.standardUserDefaults().objectForKey("user") as? String
                }
                break
            default:
                break
            }
        }else if indexPath.section == 1{
            quitLoginBtn = UIButton(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 44))
            quitLoginBtn.setTitle("退出当前账号", forState: .Normal)
            quitLoginBtn.setTitleColor(UIColor.redColor(), forState: .Normal)
            cell.addSubview(quitLoginBtn)
            quitLoginBtn.addTarget(self, action: #selector(UserViewController.quitLogin), forControlEvents: .TouchUpInside)
        }
        
        return cell
    }
    
    func quitLogin(){
        let alert = UIAlertView(title: "退出当前账号?", message: nil, delegate: self, cancelButtonTitle: "取消")
        alert.addButtonWithTitle("确定")
        alert.tag = ASK_QUIT_LOGIN_ALERT_ID
        alert.show()
    }
    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        if alertView.tag == ASK_QUIT_LOGIN_ALERT_ID{
            if buttonIndex == 1{
                if NSUserDefaults.standardUserDefaults().objectForKey("user") != nil{
                    NSUserDefaults.standardUserDefaults().removeObjectForKey("user")
                }
                if NSUserDefaults.standardUserDefaults().objectForKey("cookies") != nil{
                    NSUserDefaults.standardUserDefaults().removeObjectForKey("cookies")
                }
                let logoutResq = NSMutableURLRequest(URL: NSURL(string: "\(Fatcat.SERVER_DOMAIN_NAME)\(Fatcat.FILE_API)")!)
                logoutResq.HTTPMethod = "POST"
                logoutResq.HTTPBody = "act=logout".dataUsingEncoding(NSUTF8StringEncoding)
                NSURLSession.sharedSession().dataTaskWithRequest(logoutResq, completionHandler: { (data:NSData?, resp:NSURLResponse?, err:NSError?) in
                    if err == nil{
                        if data != nil {
                            print(String(data: data!, encoding: NSUTF8StringEncoding))
                        }
                    }
                })
                
                navigationController?.popViewControllerAnimated(true)
            }
        }
    }
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
